package exhibition.app.nexd.cn.presenter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import exhibition.app.nexd.cn.application.NexdApplication;
import exhibition.app.nexd.cn.ui.ivew.IUserInfoActivityView;
import exhibition.app.nexd.cn.utils.APIUtils;
import exhibition.app.nexd.cn.utils.OkHttpClientManager;

/**
 * user presenter
 * <p>
 * Created by wangxu on 16/4/21.
 */
public class UserInfoPresenter extends BasePresenter<IUserInfoActivityView> {

    private final String TAG = getClass().getSimpleName();

    public UserInfoPresenter(Context context, IUserInfoActivityView iView) {
        super(context, iView);
    }

    public void insertUser(@NonNull String userName, @NonNull String companyName) {

        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(companyName)) {
            iView.showToast("信息不能为空");
            return;
        }

        String insertUserURL = APIUtils.INSERT_USER +
                "&userName=" +
                userName +
                "&phoneNumber=" +
                NexdApplication.getInstance().getPhoneNum() +
                "&enterprise=" +
                companyName;

        Log.d(TAG, insertUserURL);

        OkHttpClientManager.postAsyn(insertUserURL, "", new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                iView.showToast("网络异常");
                e.printStackTrace();
            }

            @Override
            public void onResponse(String response) {

                try {
                    JSONObject insertObj = new JSONObject(response);
                    if (insertObj.getBoolean("isSuccess")) {
                        NexdApplication.getInstance().setUserId(insertObj.getInt("userId"));
                        iView.onInsertSuccess();
                    } else {
                        iView.showToast(insertObj.getString("msg"));
                    }
                } catch (JSONException e) {
                    iView.showToast("数据解析异常");
                    e.printStackTrace();
                }
            }
        });
    }

}
